from flask import Blueprint, request, jsonify, send_from_directory
from flask_cors import CORS
from flask_jwt_extended import jwt_required
from flask_login import current_user
from module import Report
from extension import db
from config import Config
from views.auth import admin_required,jwt_required
import os
from views.auth import admin_required

report_blueprint = Blueprint('report', __name__)

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in Config.ALLOWED_EXTENSIONS


@report_blueprint.route('/submit_report', methods=['POST'])
@jwt_required()
def submit_report():
    file = request.files['file']

    data = request.form
    title = data.get('title')
    user_id = data.get('uid')
    task_id = data.get('tid')

    if not title or not file or not user_id or not task_id:
        return jsonify({'error': 'Missing data'}), 400

    if not allowed_file(file.filename):
        return jsonify({'error': 'File not allowed'}), 400

    filename = file.filename
    file_path = os.path.join(Config.UPLOADED_FOLDER, filename)
    file.save(file_path)

    report = Report(title, file_path, user_id, task_id)
    db.session.add(report)
    db.session.commit()

    return jsonify({'message': 'Report submitted successfully', 'file_path': file_path}), 201


@report_blueprint.route('/check_report', methods=['GET'])
@jwt_required()
@admin_required
def check_report():
    # 假设你有一个方法来验证管理员身份
    reports = Report.query.all()
    report_list = [{'id': report.rid, 'title': report.title, 'author': report.filepath, 'pageviews': report.uid,
                    'status': report.tid} for report in reports]

    return jsonify(report_list), 200


@report_blueprint.route('/download_report/<int:report_id>', methods=['GET'])
@jwt_required()
@admin_required
def download_report(report_id):
    # 假设你有一个方法来验证管理员身份

    report = Report.query.get(report_id)
    if not report:
        return jsonify({'error': 'Report not found'}), 404

    directory = os.path.dirname(report.filepath)
    filename = os.path.basename(report.filepath)

    return send_from_directory(directory, filename, as_attachment=True)


@report_blueprint.route('/delete_report/<int:report_id>', methods=['POST'])
@jwt_required()
@admin_required
def delete_report(report_id):
    report = Report.query.get(report_id)
    if not report:
        return jsonify({'error': 'Report not found'}), 404

    db.session.delete(report)
    db.session.commit()
    return jsonify({'message': 'Report deleted successfully'}), 200





